package com.gimi.cloud.bbp.client.service.core.impl;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gimi.cloud.bbp.client.service.core.TongDunService;
import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.exception.MsgException;
import com.gimi.cloud.bbp.common.utils.DateUtil;
import com.gimi.cloud.bbp.commonService.InterfacePlatform.InterfacePlatformRequestService;
import com.gimi.cloud.bbp.dao.dao.core.TongDunDao;
import com.gimi.cloud.bbp.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.bbp.dto.core.TongDunDTO;
import com.gimi.cloud.bbp.entity.core.TongDunEntity;

import net.sf.json.JSONObject;

@Service
@Transactional
public class TongDunServiceImpl implements TongDunService {
	private static Logger logger = LoggerFactory.getLogger(TongDunServiceImpl.class);
	private final String INTERFACE_PLATFORM_UNIVERSAL_TONGDUN="interface_platform_universal_tongdun";
	private final String INTERFACE_PLATFORM_UNIVERSAL_TONGDUN_DATA="interface_platform_universal_tongdun_data";
	//最大容错次数暂时定为3次
	private final Integer MAXTIMES =3;
	@Autowired
	private TongDunDao tongDunDao;
	@Autowired
	private SysConfigDao sysConfigDao;
	@Autowired
	private InterfacePlatformRequestService requestService;


	@Override
	public String getTongDun(TongDunDTO tongDunDTO) throws Exception  {
		//查询该用户之前是否有获取过同盾
		TongDunEntity tongdunEntity = tongDunDao.getEntityByUserId(tongDunDTO.getUserId());
		//TODO 此处应该有规则，什么情况下要去再取同盾，什么情况不用

		if(tongdunEntity != null && tongdunEntity.getGetdataErrorTimes() >= MAXTIMES){
			throw new MsgException(ResponseCodeEnum.TD_DATA_ERROR_TIMES_IS_OUT_OF_TIMES);
		}
		boolean temp = true;
		if(tongdunEntity == null){
			tongdunEntity = new TongDunEntity();
			tongdunEntity.setUserId(tongDunDTO.getUserId());
			tongdunEntity.setGetdata("0");
			tongdunEntity.setAnalysis("0");
			temp = false;
		}
		String data_result = "";
		try {
			logger.info("获取同盾report_id开始");
			JSONObject config = JSONObject.fromObject(sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_TONGDUN));
			String param = config.getString("param").replace("#realName#", tongDunDTO.getName()).replace("#cardId#", tongDunDTO.getId_number()).replace("\"#phone#\"", tongDunDTO.getMobile());
			logger.info("同盾report_id，请求参数：" + param);
			String id_result = requestService.sendApiPost(param);
			logger.info("同盾report_id，返回参数：" + id_result);
			logger.info("获取同盾report_id结束");

			logger.info("获取同盾report_data开始");
			JSONObject id_resultObject = JSONObject.fromObject(id_result);
			String id_code = id_resultObject.getJSONObject("head").getString("responseCode");

			if (id_code != null && "0000".equals(id_code)) {//正确的report_id
				String reportId = id_resultObject.getJSONObject("body").getString("report_id");
				JSONObject dataconfig = JSONObject.fromObject(sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_TONGDUN_DATA));
				String data_param = dataconfig.getString("param").replace("#reportId#", reportId);
				logger.info("同盾report_data，请求参数：" + data_param);
				data_result = requestService.sendApiPost(data_param);
				logger.info("同盾report_data，返回参数：" + data_result);
			} else {
				logger.info("获取同盾report_id有问题");
				return null;
			}
		}catch (Exception e){
			//获取同盾报错
			e.printStackTrace();

		}

		logger.info("获取同盾report_data结束");

		tongdunEntity.setReportData(data_result);
		tongdunEntity.setGetdataTime(new Date());

		//user相关
		tongdunEntity.setAddTime(new Date());
		tongdunEntity.setAddUname(tongDunDTO.getName());
		tongdunEntity.setAddUid(tongDunDTO.getUserId());
		tongdunEntity.setUserId(tongDunDTO.getUserId());

		//TODO 有效时长，等风控规则
		tongdunEntity.setReportEffectionBegin(DateUtil.getNow());
		tongdunEntity.setReportEffectionEnd(DateUtil.getLateYear(1));

		JSONObject resultObject = JSONObject.fromObject(data_result);
		if(resultObject.getJSONObject("head")!=null) {
			String code = resultObject.getJSONObject("head").getString("responseCode");
			if (code != null && "0000".equals(code)) {
				tongdunEntity.setGetdata("2");
			} else {
				tongdunEntity.setGetdata("3");
			}
		}

		//如果获得分数失败，分别处理之前有记录和没记录的情况
		if(!"2".equals(tongdunEntity.getGetdata())){
			if (tongdunEntity != null){
				tongdunEntity.setGetdataErrorTimes(tongdunEntity.getGetdataErrorTimes()==null?0:tongdunEntity.getGetdataErrorTimes()+1);
			}else {
				tongdunEntity.setGetdataErrorTimes(1);
			}
		}

		tongdunEntity.setGetdataMaxTimes(MAXTIMES);
		if(temp){
			tongDunDao.updateByPrimaryKey(tongdunEntity);
		}else{
			tongDunDao.insertSelective(tongdunEntity);
		}


		logger.info("获取同盾结束");
		return "获取同盾成功";
	}
}
